package com.github.slprj.slake.common;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * @author YangXiaoLong
 * @date 2022/9/6 10:37
 */
public class SlTime {
    private final long createTime = System.nanoTime();
    private final long deadTime;

    public SlTime() {
        deadTime = createTime;
    }

    public SlTime(long timeout, TimeUnit unit) {
        deadTime = createTime + unit.toNanos(timeout);
    }

    /**
     * 过去多少时间
     */
    public long elapse(TimeUnit unit) {
        //转化为给定的单位
        return unit.convert(System.nanoTime() - createTime, TimeUnit.NANOSECONDS);
    }

    /**
     * 剩余多少时间
     */
    public long rest(TimeUnit unit) {
        return unit.convert(deadTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    /**
     * 过期时间
     */
    public long getTimeout(TimeUnit unit) {
        if (deadTime == 0) {
            return 0;
        }
        return unit.convert(deadTime - createTime, TimeUnit.NANOSECONDS);
    }
}
